package prjCode;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Reducer;


public class CalcN {

	private final static Text empty                      = new Text();

	public static class MapClass extends Mapper<LongWritable, Text, Text, IntWritable> {

		private IntWritable numAppears          = new IntWritable();
		
		@Override
		public void map(LongWritable key, Text value, Context context) throws IOException,  InterruptedException {

			String[] arr      = (value.toString()).split("/"); // % between decomposed by   /%/attack/10/	10 -> [ % between decomposed by   , %, attack, 10, 	10]

			if (arr.length < 7)
				return;

			numAppears.set(Integer.parseInt(arr[arr.length-1].substring(1)));

			context.write(empty, numAppears);


		}

	}

	public static class ReduceClass extends Reducer<Text ,IntWritable,Text ,IntWritable> {

		IntWritable val              = new IntWritable();
		private int sum;

		@Override
		public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException,  InterruptedException {
			
			sum = 0;
			for (IntWritable value : values) {
				sum += value.get();
			}
			
			val.set(sum);
			context.write(key ,val);
		}
	}



	public static class PartitionerClass extends Partitioner<Text,IntWritable> {
		// ensure that keys with same key are directed to the same reducer
		@Override
		public int getPartition(Text key,IntWritable value, int numPartitions) {
			return  Math.abs(key.hashCode()) % numPartitions;
		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = new Job(conf, "SlotY number of appearnce");
		job.setJarByClass(CalcN.class);
		job.setMapperClass(CalcN.MapClass.class);
		job.setPartitionerClass(CalcN.PartitionerClass.class);
		job.setReducerClass(CalcN.ReduceClass.class);
		job.setCombinerClass(CalcN.ReduceClass.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

}
